<style lang="less">
@import './departmentManage.less';
</style>
<template>
  <div class="search">
    <Card>
      <Row class="operation">
        <Button @click="add"
                type="primary"
                icon="md-add">添加子部门</Button>
        <Button @click="addRoot"
                icon="md-add">添加一级部门</Button>
        <!-- <Button @click="delAll"
                icon="md-trash">批量删除</Button> -->
        <!-- <Button @click="getParentList"
                icon="md-refresh">刷新</Button>
        <i-switch v-model="strict"
                  size="large"
                  style="margin-left:5px">
          <span slot="open">级联</span>
          <span slot="close">单选</span>
        </i-switch> -->
      </Row>
      <Row type="flex"
           justify="start"
           class="code-row-bg">
        <Col span="6">
        <Alert show-icon>
          当前选择编辑：
          <span class="select-title">{{editTitle}}</span>
          <a class="select-clear"
             v-if="form.id"
             @click="cancelEdit">取消选择</a>
        </Alert>
        <!-- <Input v-model="searchKey"
               suffix="ios-search"
               @on-change="search"
               placeholder="输入部门名搜索"
               clearable /> -->
        <div class="tree-bar"
             :style="{maxHeight: maxHeight}">
          <Tree ref="tree"
                :data="data"
                @on-check-change="changeSelect"
                @on-select-change="selectTree"
                :check-strictly="!strict"></Tree>
        </div>
        <Spin size="large"
              fix
              v-if="loading"></Spin>
        </Col>
        <Col span="9"
             style="margin-left:10px">
        <Form ref="form"
              :model="form"
              :label-width="85"
              :rules="formValidate">
          <FormItem label="上级部门"
                    prop="parentName">
            <Poptip trigger="click"
                    placement="right-start"
                    title="只读"
                    width="250">
              <Input v-model="form.parentName"
                     readonly />
            </Poptip>
          </FormItem>
          <FormItem label="部门名称"
                    prop="name">
            <Input v-model="form.name" />
          </FormItem>
          <FormItem label="排序值"
                    prop="orderNum">
            <InputNumber :max="1000"
                         :min="0"
                         v-model="form.orderNum"></InputNumber>
            <span style="margin-left:5px">值越小越靠前，支持小数</span>
          </FormItem>
          <Form-item>
            <Button style="margin-right:5px"
                    @click="submitEdit"
                    :loading="submitLoading"
                    type="primary"
                    icon="ios-create-outline">修改并保存</Button>
            <Button @click="handleReset">重置</Button>
            <Button @click="remove">删除</Button>
          </Form-item>
        </Form>
        </Col>
      </Row>
    </Card>

    <Modal :title="modalTitle"
           v-model="modalVisible"
           :mask-closable="false"
           :width="500">
      <Form ref="formAdd"
            :model="formAdd"
            :label-width="85"
            :rules="formValidate">
        <div v-if="showParent">
          <FormItem label="上级部门：">{{form.title}}</FormItem>
        </div>
        <FormItem label="部门名称"
                  prop="name">
          <Input v-model="formAdd.name" />
        </FormItem>
        <FormItem label="排序值"
                  prop="orderNum">
          <InputNumber :max="1000"
                       :min="0"
                       v-model="formAdd.orderNum"></InputNumber>
          <span style="margin-left:5px">值越小越靠前，支持小数</span>
        </FormItem>
      </Form>
      <div slot="footer">
        <Button type="text"
                @click="cancelAdd">取消</Button>
        <Button type="primary"
                :loading="submitLoading"
                @click="submitAdd">提交</Button>
      </div>
    </Modal>
  </div>
</template>

<script>
import {
  initDepartment,
  loadDepartment,
  addDepartment,
  editDepartment,
  deleteDepartment,
  searchDepartment
} from '@/api/index'
export default {
  name: 'department-manage',
  data() {
    return {
      loading: true,
      maxHeight: '500px',
      strict: true,
      userLoading: false,
      loadingEdit: true,
      modalVisible: false,
      selectList: [],
      selectCount: 0,
      showParent: false,
      modalTitle: '',
      editTitle: '',
      searchKey: '',
      form: {
        deptId: '',
        title: '',
        name: '',
        parentId: '',
        parentName: '',
        orderNum: 0,
        cascader: ''
      },
      formAdd: {},
      formValidate: {
        name: [{ required: true, message: '部门名称不能为空', trigger: 'blur' }]
      },
      submitLoading: false,
      data: [],
      dataEdit: [],
      users: []
    }
  },
  methods: {
    init() {
      this.getDeptList()
    },
    getDeptList() {
      this.loading = true
      initDepartment().then(res => {
        this.loading = false
        if (res.code == 0) {
          this.data = res.data
        }
      })
    },
    search() {
      if (this.searchKey) {
        this.loading = true
        searchDepartment({ title: this.searchKey }).then(res => {
          this.loading = false
          if (res.success) {
            this.data = res.result
          }
        })
      } else {
        this.getParentList()
      }
    },
    selectTree(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = ''
          }
        }
        let str = JSON.stringify(v[0])
        let data = JSON.parse(str)
        this.editTitle = data.title
        // 回显
        this.form = data
      } else {
        this.cancelEdit()
      }
    },
    cancelEdit() {
      let data = this.$refs.tree.getSelectedNodes()[0]
      if (data) {
        data.selected = false
      }
      this.$refs.form.resetFields()
      delete this.form.id
      this.editTitle = ''
    },
    selectTreeEdit(v) {
      if (v.length > 0) {
        // 转换null为""
        for (let attr in v[0]) {
          if (v[0][attr] == null) {
            v[0][attr] = ''
          }
        }
        let str = JSON.stringify(v[0])
        let data = JSON.parse(str)
        this.form.parentId = data.id
        this.form.parentName = data.title
      }
    },
    cancelAdd() {
      this.modalVisible = false
    },
    handleReset() {
      this.$refs.form.resetFields()
    },
    submitEdit() {
      this.$refs.form.validate(valid => {
        if (valid) {
          if (!this.form.deptId) {
            this.$Message.warning('请先点击选择要修改的部门')
            return
          }
          this.submitLoading = true
          editDepartment(this.form).then(res => {
            this.submitLoading = false
            if (res.code == 0) {
              this.$Message.success('编辑成功')
              this.init()
              this.modalVisible = false
            }
          })
        }
      })
    },
    submitAdd() {
      this.$refs.formAdd.validate(valid => {
        if (valid) {
          this.submitLoading = true
          addDepartment(this.formAdd).then(res => {
            this.submitLoading = false
            if (res.code == 0) {
              this.$Message.success('添加成功')
              this.init()
              this.modalVisible = false
            }
          })
        }
      })
    },
    add() {
      if (this.form.deptId == '' || this.form.deptId == null) {
        this.$Message.warning('请先点击选择一个部门')
        return
      }
      this.modalTitle = '添加子部门'
      this.showParent = true
      this.formAdd = {
        parentId: this.form.deptId,
        orderNum: 0
      }
      this.modalVisible = true
    },
    addRoot() {
      this.modalTitle = '添加一级部门'
      this.showParent = false
      this.formAdd = {
        parentId: 0,
        orderNum: 0
      }
      this.modalVisible = true
    },
    remove() {
      if (!this.form.deptId) {
        this.$Message.warning('请先点击选择要删除的部门')
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        content: '您确认要删除部门 ' + this.form.name + ' ?',
        loading: true,
        onOk: () => {
          deleteDepartment(this.form.deptId).then(res => {
            this.$Modal.remove()
            if (res.code == 0) {
              this.$Message.success('删除成功')
              this.cancelEdit()
              this.getDeptList()
            } else {
              this.$Message.error(res.msg)
            }
          })
        }
      })
    },
    changeSelect(v) {
      this.selectCount = v.length
      this.selectList = v
    },
    delAll() {
      if (this.selectCount <= 0) {
        this.$Message.warning('您还未勾选要删除的数据')
        return
      }
      this.$Modal.confirm({
        title: '确认删除',
        content:
          '您确认要删除所选的 ' + this.selectCount + ' 条数据及其下级所有数据?',
        onOk: () => {
          let ids = ''
          this.selectList.forEach(function(e) {
            ids += e.id + ','
          })
          ids = ids.substring(0, ids.length - 1)
          deleteDepartment(ids).then(res => {
            if (res.success) {
              this.$Message.success('删除成功')
              this.selectList = []
              this.selectCount = 0
              this.cancelEdit()
              this.init()
            }
          })
        }
      })
    }
  },
  mounted() {
    // 计算高度
    let height = document.documentElement.clientHeight
    this.maxHeight = Number(height - 287) + 'px'
    this.init()
  }
}
</script>